﻿using System;
using System.Text;
using System.Text.RegularExpressions;

namespace Cnblogs
{
    public class HtmlUtility
    {
        /// <summary>
        /// 将新闻、博文转化为html
        /// </summary>
        /// <param name="content">输入的html字符串</param>
        /// <returns>带有html标签的字符串</returns>
        public static string getHtml(string content)
        {
            return ConvertExtendedASCII(HtmlTransform(content));
        }

        private static string ConvertExtendedASCII(string HTML)
        {
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < HTML.Length; i++)
            {
                char ch = HTML[i];
                if (Convert.ToInt32(ch) > 0x7f)
                {
                    builder.Append("&#" + Convert.ToInt32(ch) + ";");
                }
                else
                {
                    builder.Append(ch);
                }
            }
            return builder.ToString();
        }

        /// <summary>
        /// 获取html字符串第一个img标签的src值
        /// </summary>
        /// <param name="html">输入的html字符串</param>
        /// <returns>图片url</returns>
        public static string getImageUrl(string html)
        {
            string url = "";
            var match = Regex.Match(html, "<img\\b[^<>]*?\\bsrc\\s*=\\s*[\"']?\\s*(?<imgUrl>[^\\s\"'<>]*)[^<>]*?/?\\s*>");
            if (match != null)
            {
                url = match.Groups["imgUrl"].Value;
            }
            return url;
        }

        /// <summary>
        /// 移除HTML字符串中最后一张图片
        /// </summary>
        /// <param name="html">输入的html字符串</param>
        /// <returns>移除最后一张图片后的html</returns>
        public static string RemoveLastImg(string html)
        {
            var matches = Regex.Matches(html, "<img\\b[^<>]*?\\bsrc\\s*=\\s*[\"']?\\s*(?<imgUrl>[^\\s\"'<>]*)[^<>]*?/?\\s*>");
            if (matches != null && matches.Count > 0)
            {
                html = html.Replace(matches[matches.Count - 1].Value, "");
            }
            return html;
        }

        /// <summary>
        /// 过滤HTML中的标签
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        public static string filterHTML(string html)
        {
            html = Regex.Replace(html, "</blockquote>", "");
            html = Regex.Replace(html, "<blockquote>", "");
            html = Regex.Replace(html, "<object[^>]+?>", "");
            html = Regex.Replace(html, "</object>", "");
            html = Regex.Replace(html, "width=\"\\d+\"", "");
            html = Regex.Replace(html, "height=\"\\d+\"", "");
            html = Regex.Replace(html, "<embed[^>]+?>", "");
            html = Regex.Replace(html, "</embed>", "</p>");
            html = Regex.Replace(html, "<li>", "");
            html = Regex.Replace(html, "</li>", "");
            html = Regex.Replace(html, "<p><!--more--></p>", "");
            html = Regex.Replace(html, "<img\\b[^<>]*?\\bsrc\\s*=\\s*[\"']?\\s*(?<imgUrl>[^\\s\"'<>]*)[^<>]*?/?\\s*>", "");
            html = Regex.Replace(html, "</img>", "");
            return html;
        }

        private static string HtmlTransform(string html)
        {
            html = Regex.Replace(html, "</blockquote>", "</p><br/>");
            html = Regex.Replace(html, "<blockquote>", "<p>");
            html = Regex.Replace(html, "<object[^>]+?>", "");
            html = Regex.Replace(html, "</object>", "");
            html = Regex.Replace(html, "width=\"\\d+\"", "width=\"0\"");
            html = Regex.Replace(html, "height=\"\\d+\"", "height=\"0\"");
            html = Regex.Replace(html, "<embed[^>]+?>", "<p>请访问原网页查看视/音频");
            html = Regex.Replace(html, "</embed>", "</p>");
            html = Regex.Replace(html, "<li>", "<li><span class=\"cnblogs\">");
            html = Regex.Replace(html, "</li>", "</span></li>");
            html = Regex.Replace(html, "<p><!--more--></p>", "");
            if (!GlobalFunc.IsEnableImage)
            {
                html = Regex.Replace(html, "<img\\b[^<>]*?\\bsrc\\s*=\\s*[\"']?\\s*(?<imgUrl>[^\\s\"'<>]*)[^<>]*?/?\\s*>", "");
                html = Regex.Replace(html, "</img>", "");
            }
            string str = string.Concat(new object[] { "<head><meta http-equiv=\"Content-type\" content=\"text/html;charset=utf-8\"/><meta id=\"viewport\" name=\"viewport\" content=\"width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no\"/><style type=\"text/css\">li{margin-bottom:5px;margin-left:-10px;}   .end{height:40px;} table { border-collapse: collapse; border-spacing: 0; } address, caption, cite, code, dfn, em, strong, th, var { font-style: normal; font-weight: normal; } img {width:100%; border-style:none; height:auto;text-align:center;display:block;} h1,h3,h4,h2,h5{font-size:", 16 + 4, "px;font-weight:900;} body{ font-style:normal;font-weight:700;font-family:DengXian,Microsoft YaHei,Verdana;font-size:", 16, "px;} a,a:hover,a:link,a:visited,a:active{text-decoration:none;color:#8C8C8C;border:none;background:none;} p{line-height:155%;} </style>" });
            string str2 = string.Concat(new object[] { "<head><meta http-equiv=\"Content-type\" content=\"text/html;charset=utf-8\" /><meta id=\"viewport\" name=\"viewport\" content=\"width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no\"/> <style type=\"text/css\">li{margin-bottom:5px;margin-left:-10px;} .end{height:40px;} table { border-collapse: collapse; border-spacing: 0; } address, caption, cite, code, dfn, em, strong, th, var { font-style: normal; font-weight: normal; }  img {width:100%; border-style:none; height:auto;text-align:center; display:block;} h1,h3,h4,h2,h5{font-size:", 16 + 4, "px;font-weight:900;} body{font-style:normal;font-weight:700;font-family:DengXian,Microsoft YaHei,Verdana;font-size:", 16, "px;background-color:#000000; color:#F2E9D8 } a,a:hover,a:link,a:visited,a:active{text-decoration:none;color:#8C8C8C;border:none;background:none;} p,span {line-height:155%;}</style>" });
            string str3 = "<script type='text/javascript'>\r\n                window.onLinkPressed = function() {\r\n                    var elem = event.srcElement;\r\n                    if ( elem != null ) {\r\n                        window.external.notify( elem.getAttribute('link'));\r\n                    }\r\n                    return false;\r\n                };\r\n \r\n                window.doBindLinks = function() {\r\n                    var elems = document.getElementsByTagName('a');\r\n                    for (var i = 0; i < elems.length; i++) {\r\n                        var elem = elems[i];\r\n                        var img = elem.firstChild.nodeName;\r\n                        var link = elem.getAttribute('href');\r\n                        elem.setAttribute('href', '#');\r\n                        if (img == '#text')\r\n                        {\r\n                        elem.setAttribute('link', link);\r\n                        elem.attachEvent('onmousedown', onLinkPressed);\r\n                        }\r\n                    }\r\n                var elems = document.getElementsByTagName('img');\r\n                    for (var i = 0; i < elems.length; i++) {\r\n                        var elem = elems[i];\r\n                        var link = elem.getAttribute('src');\r\n                        elem.setAttribute('link', link);\r\n                        elem.removeAttribute('width');\r\n                        elem.removeAttribute('height');\r\n                        elem.removeAttribute('class');\r\n                        elem.removeAttribute('style');\r\n                        if(link.indexOf('.gif')>0)\r\n                        {\r\n                            elem.parentNode.removeChild(elem);\r\n                        }else{\r\n                        elem.attachEvent('onmousedown', onLinkPressed);}\r\n                    }\r\n                };\r\n                </script></head> ";
            string str4 = "<body onload=\"doBindLinks();\" ><div id=\"content\">";
            html = (GlobalFunc.IsDarkTheme ? str2 : str) + str3 + str4 + html + "</div><div class=\"end\"/></body>";
            return html;
        }

        public static string SavedHtml(string html, string id)
        {
            string result = html;
            var matches = Regex.Matches(html, "<img\\b[^<>]*?\\bsrc\\s*=\\s*[\"']?\\s*(?<imgUrl>[^\\s\"'<>]*)[^<>]*?/?\\s*>", RegexOptions.IgnoreCase);
            //var matches = Regex.Matches(html, @"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>", RegexOptions.IgnoreCase);
            if (matches != null && matches.Count > 0)
            {
                for (int i = 0; i < matches.Count; i++)
                {
                    string src = matches[i].Groups["imgUrl"].Value;
                    result=result.Replace(src, id + "/" + GetParsePath(src));
                }
            }
            return result;
        }

        public static string GetParsePath(string url)
        {
            return url.Replace("://", "").Replace("/", "_");
        }
    }
}
